<template>
  <div>
    <div class="box">
      给定一个数组 nums 和一个目标值 target，在该数组中找出和为目标值的两个数 例如：输入：nums: [8,
      2, 6, 5, 4, 1, 3] ；target:7 输出：[2, 5]
      <span class="label">目标数组：{{ Q1Data }}</span>
      <span class="label">目标：18</span>
      <span class="label">结果:{{ Q1Result }}</span>
    </div>
    <div class="box">
      给定数组nums：[12,5,20,88,66,102,3,1,56,45,0,-1,86]，求数组nums中的最大值和最小值
      <span class="label">目标数组：{{ Q2Data }}</span>
      <span class="label">最大值 : {{ Q2Max }}</span>
      <span class="label">最小值 : {{ Q2Min }}</span>
    </div>
    <div class="box">
      列表转成树 将 [ { id: 1, title: "child1", parentId: 0 },{ id: 2, title: "child2", parentId: 0
      }, { id: 3, title: "child1_1", parentId: 1 },{ id: 4, title: "child1_2", parentId: 1 }, { id:
      5, title: "child2_1", parentId: 2 } ]数据结构转为树
      <span class="label">目标列表：{{ Q3Data }}</span>
      <span class="label">转换结果:{{ Q3Result }}</span>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
// 题目1
let Q1Data = ref([7, 10, 6, 5, 4, 11, 8])
let Q1Result = ref([])
const Q1fun = (arr, target) => {
  let length = arr.length
  let result = []
  arr.forEach((item, index) => {
    for (let i = index + 1; i < length; i++) {
      if (item + arr[i] === target) {
        result.push([item, arr[i]])
      }
    }
  })
  return result
}
onMounted(() => {
  Q1Result.value = Q1fun(Q1Data.value, 18)
})
// 题目2
let Q2Data = ref([15, 55, 40, 8, 76, 12, 56, 95, 0, -12, 86])
let Q2Max = ref(null)
let Q2Min = ref(null)
const Q2fun = arr => {
  let max = Math.max(...arr)
  let min = Math.min(...arr)
  return { max, min }
}
onMounted(() => {
  let { max, min } = Q2fun(Q2Data.value)
  Q2Max.value = max
  Q2Min.value = min
})
// 题目3
let Q3Data = ref([
  { id: 1, title: 'child1', parentId: 0 },
  { id: 2, title: 'child2', parentId: 0 },
  { id: 3, title: 'child1_1', parentId: 1 },
  { id: 4, title: 'child1_2', parentId: 1 },
  { id: 5, title: 'child2_1', parentId: 2 }
])
let Q3Result = ref(null)
const Q3fun = arr => {
  let result = []
  arr.forEach((item, index) => {
    if (item.parentId === 0) {
      result.push(item)
    } else {
      result.find((el, index) => {
        if (el.id === item.parentId) {
          el.children = el.children || []
          el.children.push(item)
        }
        // 下面写法会报.children无法使用push的错误
        // el.id === item.parentId ? el.children.push(item) : null
      })
    }
  })
  return result
}
onMounted(() => {
  Q3Result.value = Q3fun(Q3Data.value)
  console.log(Q3Result.value)
})
</script>
<style lang="scss">
.box {
  width: 100%;
  min-height: 200px;
  background-color: beige;
  padding: 5px;
  margin-bottom: 10px;
  font-size: 16px;
  color: black;
}
.label {
  display: block;
  margin-top: 10px;
  font-size: 20px;
}
</style>
